<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { UserApi } from '@/api-services/apis/user-api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { ApiSysUserLockOut, ApiSysUserLockQuery } from '@/api-services';
import { SysuserloginruleApi } from '@/api-services/apis/sysuserloginrule-api';
import { SysuserlockApi } from '@/api-services/apis/sysuserlock-api';
import dayjs from 'dayjs';
import { ElTag, ElPopconfirm, ElButton } from 'element-plus';
//import Button from 'element-plus/es/components/button';
//import Popconfirm from 'element-plus/es/components/popconfirm';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysUserLockQuery) =>
  fetchTableQuery<ApiSysUserLockQuery, ApiSysUserLockOut>(params, (internalParams: ApiSysUserLockQuery) =>
    getAPI(SysuserlockApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    loginRuleType: undefined,
    startDate: undefined,
    endDate: undefined,
    isManualUnlock: undefined,
    keyWords: undefined,
  },
  size: 'small',
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 130
    },
    {
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      minWidth: 170
    },

    {
      prop: 'ip',
      //dataIndex: 'ip',
      label: 'IP',
      align: 'center',
      minWidth: 150
    },
    {
      prop: 'reason',
      //dataIndex: 'reason',
      label: $t('page.manage.userLock.reason'),
      align: 'center',
      minWidth: 150
    },
    //锁定开始时间
    {
      prop: 'lockStartTime',
      //dataIndex: 'lockStartTime',
      label: $t('page.manage.userLock.lockStartTime'),
      minWidth: 170
    },
    //锁定结束时间
    {
      prop: 'lockEndTime',
      //dataIndex: 'lockEndTime',
      label: $t('page.manage.userLock.lockEndTime'),
      minWidth: 170
    },

    {
      prop: 'lockUserName',
      //dataIndex: 'lockUserName',
      label: $t('page.manage.userLock.lockUserName'),
      align: 'center',
      minWidth: 150
    },
    //是否手动解锁
    {
      prop: 'isManualUnlock',
      //dataIndex: 'isManualUnlock',
      label: $t('page.manage.userLock.isManualUnlock'),
      minWidth: 110,
      formatter: record => {
        return record.isManualUnlock ?
          <ElTag type="success">{$t('common.yesOrNo.yes')}</ElTag> :
          <ElTag type="warning">{$t('common.yesOrNo.no')}</ElTag>;
      }
    },

    //手动解锁时间
    {
      prop: 'manualUnlockTime',
      //dataIndex: 'manualUnlockTime',
      label: $t('page.manage.userLock.manualUnlockTime'),
      minWidth: 170
    },

    {
      prop: 'manualUnlockUserName',
      //dataIndex: 'manualUnlockUserName',
      label: $t('page.manage.userLock.manualUnlockUserName'),
      minWidth: 170
    },
    {
      //登录规则类别
      prop: 'loginRuleType',
      //dataIndex: 'loginRuleType',
      label: $t('page.manage.common.loginRuleType'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.loginRuleType) {
          case 1:
            return <ElTag type="primary" >{$t('page.manage.common.loginRuleTypeEnum.pwd')}</ElTag>;
          case 2:
            return <ElTag type="success" >IP</ElTag>;
          default:
            return '';
        }
      }
    },


    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      minWidth: 230,
      formatter: record => (
        <div class="flex-center gap-8px" >
          <ElPopconfirm onConfirm={() => handleManualUnlock(record)} title={$t('page.manage.userLock.unlockConfirm')}
          >
            {{
              reference: () => (
                <ElButton type="primary" plain size="small" disabled={isDisabledUnlock(record)} >
                  {$t('page.manage.userLock.unlock')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)
          }>
            {$t('common.detail')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')} >
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  editingId,
  handleAdd,
  handleEdit,
  getEditData,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const isVisibleRole = ref(false);
const editUserId = ref(0);
const handleManualUnlock = async (record: ApiSysUserLockOut) => {
  if (isDisabledUnlock(record)) {
    window.$message?.error($t('common.failed'));
    return;
  }
  // isVisibleRole.value = true;
  // 提交请求
  const [err, res] = await feature(getAPI(SysuserlockApi).manualUnlock(record.id!));

  queryDone(err, async () => {
    if (res?.data.data) {
      getDataByPage();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};

const isDisabledUnlock = (record: ApiSysUserLockOut) => {
  return (record.isManualUnlock == true || (record.lockEndTime != undefined && dayjs(record.lockEndTime) < dayjs())) ?
    true : false;
}
const handleDelete = async (id: number) => {
  const ids = [id];

  // 提交请求
  const [err, res] = await feature(getAPI(SysuserlockApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (!checkedRowKeys.value) {
    return;
  }
  const ids = checkedRowKeys.value?.map(it => Number(it))

  // 提交请求
  const [err, res] = await feature(getAPI(SysuserlockApi).batchDelete(ids?.join(',')));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <!-- 用户锁定列表 -->
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.userLock.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading" :show-add="false" @delete="handleBatchDeleted" @refresh="getData" />
        </div>

      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :edit-id="editingId"
        @submitted="getDataByPage" />

    </ElCard>
  </div>
</template>

<style scoped></style>
